package com.linxs.topcham.intefaces.controller.admin;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.web.util.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.primitives.Ints;
import com.kissme.core.orm.Page;
import com.linxs.topcham.application.org.AgencyOrgService;
import com.linxs.topcham.application.task.MonthCountService;
import com.linxs.topcham.application.task.OrderService;
import com.linxs.topcham.domain.fans.Order;
import com.linxs.topcham.domain.org.AgencyOrg;
import com.linxs.topcham.domain.task.TaskOrg;
import com.linxs.topcham.domain.user.User;

import freemarker.template.Configuration;
import freemarker.template.Template;

@Controller
@RequestMapping(value = "/admin")
public class MonthCountController {

	@Autowired
	private MonthCountService monthCountService;
	@Autowired
	private AgencyOrgService orgService;
	@Autowired
	private OrderService orderService;

	@RequestMapping(value = "/recountcommission", method = RequestMethod.POST)
	@ResponseBody
	public String recountcommission(@RequestParam("id") String id, @RequestParam("price") String price) {
		try {
			Order order = orderService.get(id);
			AgencyOrg org = orgService.queryOrgByFansUserId(order.getWeixinUserId());
			BigDecimal commission = new BigDecimal("0");
			TaskOrg task = null;
			if (null != org) {
				task = monthCountService.queryByOrgAndMonth(org.getId(), order.getRecordTime());
				commission = new BigDecimal(task.getSaleCommission());
				commission = commission.subtract(order.getCommission());
			}

			order.setPaymentCommission(new BigDecimal(price).setScale(2, BigDecimal.ROUND_DOWN));
			order.setCommission(new BigDecimal(order.getBase()).setScale(2, BigDecimal.ROUND_DOWN).multiply(order.getPaymentCommission())
					.setScale(2, BigDecimal.ROUND_DOWN));
			orderService.update(order);

			if (null != org && null != task) {
				commission = commission.add(order.getCommission());
				task.setSaleCommission(commission.toString());
				monthCountService.update(task);
			}

			return "success";
		} catch (Exception e) {
			e.printStackTrace();
			return "fail";
		}
	}

	@RequestMapping(value = "/orgmonthrecord", method = RequestMethod.GET)
	public String orgMonthRecord(Model model, HttpServletRequest request) {
		try {

			Page<TaskOrg> page = new Page<TaskOrg>();
			int pageNo = WebUtils.getCleanParam(request, "pageNo") == null ? 0 : Ints.tryParse(WebUtils.getCleanParam(request, "pageNo"));

			String orgName = WebUtils.getCleanParam(request, "orgName") == null ? "" : WebUtils.getCleanParam(request, "orgName");
			String month = WebUtils.getCleanParam(request, "month") == null ? "" : WebUtils.getCleanParam(request, "month");
			page.setPageNo(pageNo);

			if (!Strings.isNullOrEmpty(orgName)) {
				orgName = URLDecoder.decode(orgName, "UTF-8");
				Map<String, Object> params = Maps.newHashMap();
				params.put("orgName", "%" + orgName + "%");
				if (!Strings.isNullOrEmpty(month)) {
					params.put("month", month);
				}
				page.setParams(params);
				model.addAttribute("orgName", orgName);
			} else if (!Strings.isNullOrEmpty(month)) {
				Map<String, Object> params = Maps.newHashMap();
				if (!Strings.isNullOrEmpty(month)) {
					params.put("month", month);
				}
				page.setParams(params);
			}

			page = monthCountService.queryOrgMonthRecord(page.setPageNo(pageNo).setPageSize(10));
			model.addAttribute("page", page);
			model.addAttribute("month", month);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "/month/list";
	}

	@RequestMapping(value = "/mymonthrecord", method = RequestMethod.GET)
	public String mymonthrecord(Model model, HttpServletRequest request) {
		try {

			Page<TaskOrg> page = new Page<TaskOrg>();
			int pageNo = WebUtils.getCleanParam(request, "pageNo") == null ? 0 : Ints.tryParse(WebUtils.getCleanParam(request, "pageNo"));

			String month = WebUtils.getCleanParam(request, "month") == null ? "" : WebUtils.getCleanParam(request, "month");
			String orgName = orgService.get(((User) request.getSession().getAttribute("user")).getId().toString()).getOrgName();
			page.setPageNo(pageNo);

			Map<String, Object> params = Maps.newHashMap();
			params.put("orgName", "%" + orgName + "%");
			params.put("month", month);

			page.setParams(params);

			page = monthCountService.queryOrgMonthRecord(page.setPageNo(pageNo).setPageSize(10));
			model.addAttribute("page", page);
			model.addAttribute("month", month);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "/month/mylist";
	}

	@RequestMapping(value = "ordermonthrecord", method = RequestMethod.GET)
	public String orderMonthRecord(Model model, HttpServletRequest request) {
		Page<Order> page = new Page<Order>();
		int pageNo = WebUtils.getCleanParam(request, "pageNo") == null ? 0 : Ints.tryParse(WebUtils.getCleanParam(request, "pageNo"));

		String orderid = WebUtils.getCleanParam(request, "orderid") == null ? "" : WebUtils.getCleanParam(request, "orderid");
		String month = WebUtils.getCleanParam(request, "month") == null ? "" : WebUtils.getCleanParam(request, "month");

		Map<String, Object> params = Maps.newHashMap();
		params.put("orderid", orderid);
		params.put("month", month);

		page.setParams(params);

		page = monthCountService.queryOrderMonthRecord(page.setPageNo(pageNo).setPageSize(10));
		page.setResult(countCommision(page.getResult()));
		model.addAttribute("page", page);
		model.addAttribute("orderid", orderid);
		model.addAttribute("month", month);
		return "/month/orderList";
	}

	@SuppressWarnings("deprecation")
	@RequestMapping(value = "/ordermonthexport", method = RequestMethod.GET)
	public void orderMonthExport(HttpServletRequest request, HttpServletResponse response) {
		String month = request.getParameter("month");
		String path = request.getRealPath("/");
		String docName = "已签收订单.xls";
		String templateName = "finishorder.ftl";
		path = path + "/WEB-INF/views/";
		File documentFile = new File(path + docName);
		Map<String, Object> data = new HashMap<String, Object>();
		
		List<Order> result = Lists.newArrayList();
		if(Strings.isNullOrEmpty(month)) {
			result = monthCountService.query();
		} else {
			result = monthCountService.queryByMonth(month);
			
		}
		
		result = countCommision(result);
		List<Order> orders = Lists.newArrayList();
		for(Order o : result) {
			AgencyOrg org = orgService.queryOrgByFansUserId(o.getWeixinUserId());
			if(null != org) {
				o.setOrgId(org.getOrgName()); 
			}
			
			orders.add(o);
		}
		data.put("orders", orders);
		exportToDocumentTemplate(path, templateName, documentFile, data);
		download(request, response);
	}

	private List<Order> countCommision(List<Order> result) {
		List<Order> orders = Lists.newArrayList();
		for(Order order : result) {
			AgencyOrg org = orgService.get(order.getOrgId());
			if (null != org) {
				if (order.getAddress().indexOf(org.getAreas()) != -1 || "全国地区".equals(org.getAreas())) {
					order.setBase("0.05");
					order.setCommission(new BigDecimal("0.05").setScale(2, BigDecimal.ROUND_DOWN).multiply(order.getPayment())
							.setScale(2, BigDecimal.ROUND_DOWN));
				} else {
					order.setBase("0.03");
					order.setCommission(new BigDecimal("0.03").setScale(2, BigDecimal.ROUND_DOWN).multiply(order.getPayment())
							.setScale(2, BigDecimal.ROUND_DOWN));
				}
				order.setOrgId(org.getId());
			} else {
				order.setBase("0.03");
				order.setCommission(new BigDecimal("0.03").setScale(2, BigDecimal.ROUND_DOWN).multiply(order.getPayment())
						.setScale(2, BigDecimal.ROUND_DOWN));

			}
			orders.add(order);
		}
		return orders;
	}

	private void download(HttpServletRequest request, HttpServletResponse response) {
		try {

			response.setContentType("text/html;charset=UTF-8");
			request.setCharacterEncoding("UTF-8");
			BufferedInputStream bis = null;
			BufferedOutputStream bos = null;

			String ctxPath = request.getSession().getServletContext().getRealPath("/");
			String downLoadPath = ctxPath + "/WEB-INF/views/已签收订单.xls";

			long fileLength = new File(downLoadPath).length();

			String agent = request.getHeader("User-Agent");
			String fileName = "已签收订单.xls";
			boolean isMSIE = (agent != null && agent.indexOf("MSIE") != -1);
			if (isMSIE) {
				fileName = java.net.URLEncoder.encode(fileName, "UTF8");
			} else {
				fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
			}

			response.setHeader("Content-disposition", "attachment; filename=" + fileName);
			response.setHeader("Content-Length", String.valueOf(fileLength));

			bis = new BufferedInputStream(new FileInputStream(downLoadPath));
			bos = new BufferedOutputStream(response.getOutputStream());
			byte[] buff = new byte[2048];
			int bytesRead;
			while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
				bos.write(buff, 0, bytesRead);
			}
			bis.close();
			bos.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void exportToDocumentTemplate(String path, String templateName, File outFile, Map<String, Object> map) {

		Configuration cfg = new Configuration();
		Template template = null;
		Writer out = null;
		try {
			cfg.setDirectoryForTemplateLoading(new File(path));
			cfg.setDefaultEncoding("UTF-8");
			template = cfg.getTemplate(templateName);
			template.setEncoding("UTF-8");
			out = new OutputStreamWriter(new FileOutputStream(outFile), "UTF-8");
			template.process(map, out);

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				out.flush();
				out.close();

			} catch (Exception e2) {
				e2.printStackTrace();
			}

		}

	}

	// public invoke() {
	// String path = ServletActionContext.getServletContext().getRealPath("/");
	// String docName = "要生成的文档名.doc";
	// String templateName = "刚才保存好了的模版文件名.ftl";
	// File documentFile = new File(path + docName);
	// Map<String, Object> data = new HashMap<String, Object>();
	// data.put("content", "这里是要填充到模版里的内容。。。");
	// exportToDocumentTemplate(path, templateName, documentFile, data);
	// }

}
